package com.rcd.viatornisl.android.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rcd.viatornisl.android.LoadingActivity;
import com.rcd.viatornisl.android.R;
import com.rcd.viatornisl.android.model.Interest;
import com.rcd.viatornisl.android.model.adapters.InterestAdapter;

public class NavigationDrawerFragment extends Fragment {

	private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
	private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";	
	private NavigationDrawerCallbacks _Callbacks;
	private ActionBarDrawerToggle _DrawerToggle;
	private DrawerLayout _DrawerLayout;
	private ListView _DrawerListView;
	private View _FragmentContainerView;
	private int _CurrentSelectedPosition = 0;
	private boolean _FromSavedInstanceState;
	private boolean _UserLearnedDrawer;
	
	private ActionBar getActionBar() {
		// Provide the return
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }
	
	private void showGlobalContextActionBar() {
    	// Get the action bar
        ActionBar actionBar = getActionBar();
        
        // Setup the action bar
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.application_name);
    }
	
	private void selectItem(int position, Bundle parameters) {														
		// get the current selected position value
		this._CurrentSelectedPosition = position;
		
		// If not null
		if (_DrawerListView != null) {
			// Set the selected item on the drawer list view
			this._DrawerListView.setItemChecked(position, true);
		}
		
		// If not null
		if (this._DrawerLayout != null) {
			// Close the drawer layout
			this._DrawerLayout.closeDrawer(this._FragmentContainerView);
		}
		
		// If not null
		if (this._Callbacks != null) {
			// Set the call back passing the position
			this._Callbacks.onNavigationDrawerItemSelected(position, parameters);
		}
	}
	
	public static interface NavigationDrawerCallbacks {
		// Set the call back
        void onNavigationDrawerItemSelected(int position, Bundle params);
    }
	
	public boolean isDrawerOpen() {
		// Check if it is a drawer option and provide the return
        return this._DrawerLayout != null && this._DrawerLayout.isDrawerOpen(this._FragmentContainerView);
    }
	
	public void setup(int fragmentId, DrawerLayout drawerLayout) {
		// Get the fragment container view
		this._FragmentContainerView = super.getActivity().findViewById(fragmentId);
		
		// Retrieve the drawer layout
        this._DrawerLayout = drawerLayout;
        this._DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        
        // Get the action bar
        ActionBar actionBar = this.getActionBar();
        
        // Setup the action bar
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        
        this._DrawerToggle = new ActionBarDrawerToggle(
    		super.getActivity(),
    		this._DrawerLayout,
    		R.drawable.ic_drawer,
    		R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {
        	
        	@Override
            public void onDrawerClosed(View drawerView) {
        		// Default operations
        		super.onDrawerClosed(drawerView);
                
                // If not added
                if (!(NavigationDrawerFragment.super.isAdded())) {
                	// Quit
                    return;
                }

                // Support invalidate options menu
                NavigationDrawerFragment.super.getActivity().supportInvalidateOptionsMenu();
            }
        	
        	@Override
            public void onDrawerOpened(View drawerView) {
        		// Default operations
                super.onDrawerOpened(drawerView);
                
                // If not added
                if (!(NavigationDrawerFragment.super.isAdded())) {
                	// Quit
                    return;
                }

                // Check the flag
                if (!(NavigationDrawerFragment.this._UserLearnedDrawer)) {
                	// Update the flag value
                	NavigationDrawerFragment.this. _UserLearnedDrawer = true;
                	
                	// Get the default shared preferences
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    
                    // Edit the default shared preferences
                    sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
                }

                // Support invalidate options menu
                NavigationDrawerFragment.super.getActivity().supportInvalidateOptionsMenu();
            }
        };
        
        // If enabled
        if ((!(_UserLearnedDrawer)) && (!(_FromSavedInstanceState))) {
        	// Open the drawer layout object
            this._DrawerLayout.openDrawer(_FragmentContainerView);
        }
        
        // Post an event on the drawer layout object
        this._DrawerLayout.post(new Runnable() {
            @Override
            public void run() {
            	// Sycn the thread state
            	NavigationDrawerFragment.this._DrawerToggle.syncState();
            }
        });
        
        // Set the drawer layout with the drawer toggle
        this._DrawerLayout.setDrawerListener(this._DrawerToggle);
	}

	@Override
    public void onSaveInstanceState(Bundle outState) {
		// Default operations
        super.onSaveInstanceState(outState);
        
        // Set the value on the bundle object
        outState.putInt(STATE_SELECTED_POSITION, this._CurrentSelectedPosition);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// Default operations
		super.onCreate(savedInstanceState);
		
		// Get the default shared preferences
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(super.getActivity());
		
		// Set the user learned drawer
		this._UserLearnedDrawer = sharedPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false);
		
		// If there is a valid saved instance state
		if (savedInstanceState != null) {
			// Set the current selected position
			this._CurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
			
			// Mask as from saved instance state
			this._FromSavedInstanceState = true;
		}
		
		// Set the selected item position
		this.selectItem(this._CurrentSelectedPosition, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// Default operations
		super.onActivityCreated(savedInstanceState);
		
		// Mark as has option menu
		super.setHasOptionsMenu(true);
	}
	
	/*
	 * This is the entry point to change the menu
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Get the correct generic list type
		Type listType = new TypeToken<ArrayList<Interest>>() {}.getType();
				
		// Get a drawer list view
		this._DrawerListView = (ListView) inflater.inflate(R.layout.navigation_drawer_fragment, container, false);
		
		// Set a listener to the drawer list view item
		this._DrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// Set the selected item position
				NavigationDrawerFragment.this.selectItem(position, ((InterestAdapter.InterestHolder)view.getTag())._InterestBundle);						        		
			}
		});
		
		// Adapter items to the drawer list view
		this._DrawerListView.setAdapter(new InterestAdapter(this.getActionBar().getThemedContext(), 
			R.layout.interest_list_item,
			(List<Interest>) new Gson().fromJson(PreferenceManager.getDefaultSharedPreferences(this.getActivity()).getString(LoadingActivity.INTERESTS_STATE, ""), listType)));
		
		// Set the default item checked from the drawer list view
		this._DrawerListView.setItemChecked(this._CurrentSelectedPosition, true);
		
		// Provide the return
		return this._DrawerListView;
	}
	
	@Override
    public void onAttach(Activity activity) {
		// Default operations
        super.onAttach(activity);
        
        try {
        	// Cast for an navigation drawer callbacks object
            this._Callbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
        	// On error
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }
	
	@Override
    public void onDetach() {
		// Default operations
        super.onDetach();
        
        // Reset the callback
        this._Callbacks = null;
    }
	
    @Override
    public void onConfigurationChanged(Configuration newConfiguration) {
    	// Default operations
        super.onConfigurationChanged(newConfiguration);
        
        // Set a new configuration to the drawer toggle
        this._DrawerToggle.onConfigurationChanged(newConfiguration);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	// Check if the drawer layout is valid
        if ((this._DrawerLayout != null) && (this.isDrawerOpen())) {
        	// Show the global action bar
            this.showGlobalContextActionBar();
        }
        
        // Default operations
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// Check the selected item from the drawer toggle
        if (this._DrawerToggle.onOptionsItemSelected(item)) {
        	// Quit
            return true;
        }

        /*TODO: Maybe remove this later
        if (item.getItemId() == R.id.action_example) {
            Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }
         */

        // Default operations
        return super.onOptionsItemSelected(item);
    }

}
